using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using KRBTabControl;
using ScintillaNET;

namespace FizzDevelop
{
	// This class represents a TabPage that contains an editor for a specific file.
	public class FizzFileTab : FizzTab
	{
		private bool saved;		// Is the tab's file saved? 
		public bool isNewFile;	// Is the file just created (marked as saved but really not)
		private FizzFile file;	// The file contained in the tabcontrol
		public object Editor;	// The editor this tab contains, e.g. CodeEditor, WidgetEditor
		public List<string> BinaryFiles;	// The path to the binary executables, if they exist

		public FizzFileTab()
		{
			ImageIndex = 1;
			Saved = true;
			isNewFile = true;
		}

		public FizzFile File
		{
			get { return file; }
		}

		public bool Saved
		{
			get { return saved; }
			set
			{
				saved = value;
				if (saved)
					ImageIndex = -1;
				else
					ImageIndex = 1;
				isNewFile = false;
			}
		}

		public void OpenFile(String path)
		{
			file = new FizzFile(path);
			FizzCodeEditor editor = (FizzCodeEditor)Editor;
			editor.Text = System.IO.File.ReadAllText(path);
			string longest = "";
			foreach (Line line in ((FizzCodeEditor)Editor).Lines)
			{
				if (CreateGraphics().MeasureString(line.Text, new Font("Consolas", 8.25f)).Width > CreateGraphics().MeasureString(longest, new Font("Consolas", 8.25f)).Width)
					longest = line.Text;
			}
			editor.Scrolling.HorizontalWidth = (int)CreateGraphics().MeasureString(longest, new Font("Consolas", 8.25f)).Width + 50;
			editor.UndoRedo.EmptyUndoBuffer();
			Text = Path.GetFileName(path);
			editor.Language = Util.ExtToLanguage(Path.GetExtension(path));
			isNewFile = false;
			Saved = true;
		}

		public bool Save()
		{
			if (!Editor.Equals(null) && (!saved || isNewFile))
			{
				if (File == null)
					return SaveAs();
				else
				{
					System.IO.File.WriteAllText(File.Path, ((FizzCodeEditor)Editor).Text);
					Saved = true;
					isNewFile = false;
					return Saved;
				}
			}
			return false;
		}

		public bool SaveAs()
		{
			if (!Editor.Equals(null))
			{
				SaveFileDialog saveDialog = new SaveFileDialog();
				saveDialog.Title = "Save As...";
				if (saveDialog.ShowDialog() == DialogResult.OK) file = new FizzFile(saveDialog.FileName);
				else return false;
				Text = Path.GetFileName(File.Path);
				System.IO.File.WriteAllText(File.Path, ((FizzCodeEditor)Editor).Text);
				Saved = true;
				isNewFile = false;
				return true;
			}
			return false;
		}
	}
}